import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Param} from '../../shared/class/param';
import {Observable} from 'rxjs/Observable';
import {Result} from '../../shared/class/result';
import {Subject} from 'rxjs/Subject';
import {PageResult} from '../../shared/class/page-result';
import * as _ from 'underscore';

@Injectable()
export class UserService {

  constructor(
    private http: HttpClient
  ) {
  }

  getUserList(param: Param): Observable<Result> {
    const subject = new Subject<Result>();
    this.http.get<any[]>('assets/json/user/user.list.json').subscribe(res => {
      const count = res.length;
      const list = res.splice((param.pageNo - 1) * param.pageSize, param.pageSize);
      const page = new PageResult({list: list, count: count});
      const result = new Result({code: 200, msg: null, data: page});
      subject.next(result);
    });
    return subject.asObservable();
  }

  getUser(id: any): Observable<any> {
    const subject = new Subject();
    this.http.get<any[]>('assets/json/user/user.list.json').subscribe(res => {
      const result = _.find(res, obj => obj['id'] === parseInt(id, 10));
      subject.next(result);
    });
    return subject.asObservable();
  }
}
